package work.huangxin.share.controller.user;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import work.huangxin.share.domain.admin.UserAdminSys;
import work.huangxin.share.domain.other.Audience;
import work.huangxin.share.domain.other.WXSessionModel;
import work.huangxin.share.service.UserAdminSysService;
import work.huangxin.share.util.JWTUtil;
import work.huangxin.share.util.RedisUtil;
import work.huangxin.share.util.ThreadLocalUtil;
import work.huangxin.share.util.common.JsonUtils;
import work.huangxin.share.util.status.BaseResponse;
import work.huangxin.share.util.status.CodeEnum;
import work.huangxin.share.util.status.ResponseData;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author 季台星
 * @Date 2023 03 31 14 27
 * 后台管理系统用户相关接口
 */
@RestController
@RequestMapping("/wx/admin/api")
public class UserAdminSysController {
    /**
     * JWT生成令牌使用（加密算法）
     */
    @Resource
    private Audience audience;
    @Autowired
    private UserAdminSysService userAdminSysService;
    @PostMapping("/loginAdmin")
    public BaseResponse LoginAdmin(@RequestBody UserAdminSys userAdminSys){
        UserAdminSys userAdminSysByDB = userAdminSysService.checkPassword(userAdminSys);
        if (Objects.isNull(userAdminSysByDB)){
            return ResponseData.error(403, "用户名或密码错误");
        }
        //用户校验成功，生成token返回给前端，后续由拦截器鉴权
        String jwt = JWTUtil.createJWT(audience, userAdminSysByDB);
        return ResponseData.success(jwt);
    }
    @Autowired
    private RedisUtil redisUtil;
    @GetMapping("/getInfo")
    public BaseResponse getAdminInfo(HttpServletRequest request){
        UserAdminSys admin = (UserAdminSys) request.getSession().getAttribute("admin");
        Long userId = ThreadLocalUtil.get();
        WXSessionModel user1 = (WXSessionModel) redisUtil.get("user:" + userId);
        //UserAdminSys admin = (UserAdminSys)redisUtil.get("admin:" + ThreadLocalUtil.get());

        if (Objects.isNull(admin)){
            return ResponseData.error(CodeEnum.SIGNATURE_NOT_ALLOW);
        }
        admin.setPassword("");
        return ResponseData.success(admin);
    }
    @PostMapping("/logout")
    public BaseResponse logOutAdmin(HttpServletRequest request){
        //移除session中的admin对象
        request.getSession().removeAttribute("admin");
        Long userId = ThreadLocalUtil.get();
        redisUtil.del("admin"+userId);
        String authorization = request.getHeader("authorization");
        return ResponseData.success();
    }

}
